package ui;

import core.*;
import java.awt.EventQueue;
import ui.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import javax.swing.JOptionPane;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;


/**
 *
 * @author Sakis Vtdk
 */
public class DbVersioning {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
		//Setup our logger
		DOMConfigurator.configure(CONFIG_FOLDER + File.separator +"log4j.xml");

		log.info("Starting application "+ APPLICATION_NAME +" "+ APPLICATION_VERSION);
		
		log.info("Checking folder structure...");
		if(checkFolderStructure())
		{
			log.info("Folder strucutre ok.");
			EventQueue.invokeLater(
					new Runnable() {
				@Override
				public void run() {
					ApplicationWindow.getApplicationWindow(APPLICATION_NAME +" "+ APPLICATION_VERSION).setVisible(true);
				}
			});
		}
		else
		{
			log.fatal("The folder structure is damaged and the application cannot initialize.");
			JOptionPane.showMessageDialog(null, "The folder structure is damaged and the application cannot initialize.", "Error!", JOptionPane.ERROR_MESSAGE);
			System.exit(-1);
		}
		 
    }

	/**
	 * Checks if the folder structure required by the application is in place
	 * 
	 * @return true if the folder structure exists as expected, false otherwise
	 */
	private static Boolean checkFolderStructure()
	{
		Boolean foldersExist = true;

		//check data folder
		File dataFolder = new File(DEFAULT_DATA_FOLDER);

		if(!dataFolder.exists() || !dataFolder.isDirectory())
		{
			foldersExist = false;
		}
		else
		{
			//check changes folder
			File changesFolder = new File(DEFAULT_CHANGES_FOLDER);

			if(!changesFolder.exists() || !changesFolder.isDirectory())
			{
				foldersExist = false;
			}
		}

		//check config folder
		File configFolder = new File(CONFIG_FOLDER);
		if(!configFolder.exists() || !configFolder.isDirectory())
		{
			foldersExist = false;
		}

		return foldersExist;
	}

	/**
	 * Saves a database object to a file
	 * 
	 * @param filename The name of the file
	 * @param database The database object to be saved
	 */
	public static void saveDatabaseToFile(String filename, Database database)
	{
		try
		{
			ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(DEFAULT_DATA_FOLDER + File.pathSeparator + filename +"."+ FILE_EXTENSION));
			outputStream.writeObject(database);
			outputStream.close();
		}
		catch(IOException e)
		{
			log.fatal("The following error occured when trying to save the file: "+ e.getMessage());
		}
	}

	/**
	 * Reads a database object from the file
	 * 
	 * @param filename the file from which we will read the database
	 * @return The Database object from the file
	 */
	public static void readDatabaseFromFile(String filename)
	{
		Database db = null;
		try
		{
			ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(DEFAULT_DATA_FOLDER + File.separator + filename +"."+ FILE_EXTENSION));

			try 
			{
				db = Database.getDatabase(inputStream);
			} 
			catch (ClassNotFoundException e) 
			{
				log.fatal("The following error occured when trying to read from file: "+ e.getMessage());
			}
		}
		catch(IOException e)
		{
			log.fatal("The following error occured when trying to open the file: "+ e.getMessage());
		}
	}

	/**
	 * Returns the default title of the application containing the application name and the version
	 * 
	 * @return A string containing the application name and the version
	 */
	public static String getDefaultTitle()
	{
		return APPLICATION_NAME +" "+ APPLICATION_VERSION;
	}
	
	/**
	 * The default sql engine of the application
	 */
	public final static String DEFAULT_SQL_ENGINE = "mysql";

	/**
	 * The default configuration folder
	 */
	public final static String CONFIG_FOLDER = "config";

	/**
	 * The path to the folder containing the data of the application
	 */
	public final static String DEFAULT_DATA_FOLDER = "data";

	/**
	 * The path to the folder containing the changes of all the projects
	 */
	public final static String DEFAULT_CHANGES_FOLDER = DEFAULT_DATA_FOLDER + File.separator +"changes";

	/**
	 * The extension of the files used by the application
	 */
	public final static String FILE_EXTENSION = "dbv";

	/**
	 * The extension of the sql files
	 */
	public final static String SQL_FILE_EXTENSION = "sql";

	/**
	 * The OS on which the application is running
	 */
	public final static String OS = System.getProperty("os.name").toLowerCase();

	/**
	 * The name of the application
	 */
	private final static String APPLICATION_NAME = "DB Versions";

		/**
	 * The version of the application
	 */
	private final static String APPLICATION_VERSION = "0.1";

	/**
	 * The logger instance
	 */
	private static Logger log = Logger.getLogger(DbVersioning.class);
}
